<template>
  <div class="SuccessTab">
    <el-card>
      <!-- 搜索筛选 -->
      <el-form :inline="true" class="user-search">
        <el-form-item>
          <el-form-item label="搜索：">
            <el-input clearable v-model="formInline.name" @clear="clearSearch('name')" placeholder="姓名"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input clearable v-model="formInline.identity" @clear="clearSearch('identity')" placeholder="支付宝账号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input clearable v-model="formInline.outBizNo" @clear="clearSearch('outBizNo')" placeholder="订单编号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-loading="selectUserLoading" @click.native="handleUserDataSelectChange" clearable
                       v-model="formInline.operatorId" filterable placeholder="请选择用户">
              <el-option
                  v-for="(item,index) in userList"
                  :key="index"
                  :label="item.name"
                  :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item style="margin-left: 52px;">
          <el-form-item>
            <el-input
                maxlength="8"
                oninput="value=value.replace(/[^\d.]/g,'')"
                v-model="formInline.transAmount"
                placeholder="请输入金额(单位：元)"
                @clear="clearSearch('transAmount')"
                clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-date-picker
                @change="handleSearchSelectChange"
                v-model="formInline.timeForm"
                type="datetimerange"
                :picker-options="TimeDataPicker"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="searchOrderBtn">搜索</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delOrderBtn">清除</el-button>
          </el-form-item>
        </el-form-item>
      </el-form>
      <el-table
          @row-click="getNowColumn"
          :header-cell-style="thStyleFun"
          :cell-style="cellStyleFun"
          height="520px"
          ref="multipleTable"
          :data="tableData"
          border
          tooltip-effect="dark"
          @selection-change="handleSelectionChange"
          style="width: 100%">
        <el-table-column
            fixed="left"
            type="selection"
            width="50">
        </el-table-column>
        <el-table-column
            header-align="center"
            prop="outBizNo"
            width="120"
            label="订单编号">
        </el-table-column>
        <el-table-column
            header-align="center"
            prop="identity"
            width="180"
            label="支付宝账号">
        </el-table-column>
        <el-table-column
            header-align="center"
            prop="name"
            label="收款人姓名">
        </el-table-column>
        <el-table-column
            header-align="center"
            prop="mobile"
            width="120"
            label="手机">
        </el-table-column>
        <el-table-column
            header-align="center"
            prop="transAmount"
            label="金额">
        </el-table-column>
        <el-table-column
            header-align="center"
            prop="statusTxt"
            label="状态">
          <template slot-scope="scope">
            <el-tag
                :type="showStatus[scope.row.status]"
                disable-transitions>{{ scope.row.statusTxt }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            header-align="center"
            prop="operator"
            label="操作者"
            width="90">
        </el-table-column>
        <el-table-column
            show-overflow-tooltip
            header-align="center"
            prop="remark"
            width="230"
            label="转账理由">
        </el-table-column>
        <el-table-column
            width="160"
            show-overflow-tooltip
            header-align="center"
            prop="createTime"
            label="创建时间">
        </el-table-column>
        <el-table-column
            width="160"
            show-overflow-tooltip
            header-align="center"
            prop="transDate"
            label="交易时间">
        </el-table-column>
      </el-table>
      <el-pagination
          class="page-box"
          :page-count="pageInfo.totalPage"
          :current-page="pageInfo.pageNo"
          :page-size="pageInfo.pageSize"
          :total="pageInfo.totalNum"
          @size-change="handleSizeChange"
          @current-change="onSelectPageHandler"
          :page-sizes="pageInfo.pageSizeArr"
          layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </el-card>
    <!-- 支付异常界面 -->
    <el-dialog @open="getErrorInfoByNum" class="payModelClass" top="0.5vh" :center="true" :title="`支付异常详情`"
               :visible.sync="payFormErrorVisible"
               width="30%" @click='closeDialog("error")'>
      <el-form label-width="120px" ref="editPayForm" :model="payForm" :rules="rules">
        <el-form-item label="商户订单号" prop="outBizNo" class="payModelClass-item">
          <span>{{ payForm.outBizNo }}</span>
        </el-form-item>
        <el-form-item label="收款人姓名" prop="name" class="payModelClass-item">
          <span>{{ payForm.name }}</span>
        </el-form-item>
        <el-form-item label="支付宝账号" prop="identity" class="payModelClass-item">
          <span>{{ payForm.identity }}</span>
        </el-form-item>
        <el-form-item label="转账金额" prop="transAmount" class="payModelClass-item">
          <span>{{ payForm.transAmount }}</span>
        </el-form-item>
        <el-form-item label="收款人联系电话" prop="mobile">
          <span>{{ payForm.mobile }}</span>
        </el-form-item>
        <el-form-item label="转账时间" prop="transDate">
          <span>{{ payForm.transDate }}</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-tag
              type="danger"
              disable-transitions>{{ payForm.statusTxt }}
          </el-tag>
        </el-form-item>
        <el-form-item label="操作员ip地址" prop="ipAddr">
          <span>{{ payForm.ipAddr }}</span>
        </el-form-item>
        <el-form-item label="转账理由" prop="remark">
          <span>{{ payForm.remark }}</span>
        </el-form-item>
        <el-form-item label="订单创建时间" prop="createTime">
          <span>{{ payForm.createTime }}</span>
        </el-form-item>
        <el-form-item label="修改时间" prop="updateTime">
          <span>{{ payForm.updateTime }}</span>
        </el-form-item>
        <el-form-item label="异常原因" prop="desc">
          <el-alert
              show-icon
              :closable="false"
              :title="ErrorMsg"
              type="error">
          </el-alert>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click='closeDialog("error")'>关闭</el-button>
        <el-button type="primary" :loading="loading" class="title" @click="handleEdit">转账
        </el-button>
      </div>
    </el-dialog>
    <!-- 编辑界面 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="editFormVisible" width="30%"
               @click='closeDialog("edit")'>
      <el-form label-width="120px" ref="editForm" :model="editForm" :rules="payRules">
        <el-form-item label="订单编号" prop="outBizNo">
          <el-input readonly="true" v-model="editForm.outBizNo" placeholder="请输入订单编号"></el-input>
        </el-form-item>
        <el-form-item label="金额(单位：元)" prop="transAmount">
          <el-input
              maxlength="8"
              oninput="value=value.replace(/[^\d.]/g,'')"
              v-model="editForm.transAmount"
              placeholder="请输入金额(单位：元)">
          </el-input>
        </el-form-item>
        <el-form-item label="支付宝账号" prop="identity">
          <el-input v-model="editForm.identity" auto-complete="off" placeholder="请输入支付宝账号"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="转账理由" prop="remark">
          <el-input type="textarea" v-model="editForm.remark" placeholder="请输入转账理由"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click='closeDialog("edit")'>取消</el-button>
        <el-button type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.page-box {
  margin: 10px auto;
  position: fixed;
}

.userRole {
  width: 100%;
}

.payModelClass {
  .el-form {
    .payModelClass-item {
      border: 2px solid #F56C6C;
    }
  }
}

.right {
  float: right;
  button {
    margin-top: 20px;
    margin-left: 25px;
  }

  .error-msg {
    font-size: 14px;
    text-align: right;
    margin-right: 10px;
    color: #F56C6C;

    .red {
      margin-right: 3px;
      color: #000;
    }
  }
}

.money-count {
  .count-item {
    margin-right: 10px;
    cursor: pointer;

    &:last-child {
      margin-right: 0;
    }
  }
}


</style>

<script>
import {orderReason, orderList, orderTransfer, orderDel, orderTransferBatch, orderMod} from '@/api/order';
import {getList} from '@/api/user';
import {getToken} from '@/utils/auth';
import dayjs from 'dayjs';

export default {
  data() {
    const TimeDataPicker = {
      shortcuts: [{
        text: '当日交易',
        onClick(picker) {
          let start = new Date(new Date().setHours(0,0,0,0));
          let end = new Date(new Date().setHours(23, 59, 59, 999));
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近一周',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit('pick', [start, end]);
        }
      }, {
        text: '最近一个月',
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          picker.$emit('pick', [start, end]);
        }
      }]
    };
    const token = getToken();
    const uploadUrl = process.env.VUE_APP_apiUrl + "/order/add/batch";
    return {
      multipleSelection: [],
      title: '添加用户',
      loading: false,
      TimeDataPicker,
      token,
      uploadUrl,
      editFormVisible: false, //控制编辑页面显示与隐藏
      payFormVisible: false, //支付模态框
      payFormErrorVisible: false, //异常模态框
      trFormVisible: false, //批量转账模态框
      editForm: {
        identity: '',
        mobile: '',
        name: '',
        outBizNo: '',
        remark: '',
        transAmount: ''
      },
      payForm: {
        name: "",
        operatorId: "", // 搜索用户下拉框选中的值
        identity: "",
        outBizNo: "",
        transAmount: "",
        transDate: "",
        status: "",
        ipAddr: "",
        remark: "",
        createTime: "",
        mobile: "",
        updateTime: "",
        payPassword: "" // 支付密码
      },
      showStatus: {
        0: 'warning',
        1: 'success',
        '-1': 'danger',
      },
      showStatusTxt: {
        0: '未处理',
        1: '支付详情',
        '-1': '异常信息',
      },
      statusTxt: {
        0: '未处理',
        1: '处理成功',
        '-1': '处理异常',
      },
      trForm: {
        payPwd: ""
      },
      ErrorMsg: "",
      // 转账金额总显示
      AmountCount: {
        successCount: "0",
        failCount: "0",
        totalAmount: "0",
      },
      formInline: {
        name: "",
        operatorId: "", // 搜索用户下拉框选中的值
        identity: "",
        outBizNo: "",
        transAmount: "",
        transDate: "",
        status: "",
        timeForm: [], // 时间筛选
        startTime: "",
        endTime: "", // 时间筛选
      },
      options: [
        {label: "禁用", value: 0},
      ],
      payType: [
        {key: "未处理", value: 0},
        {key: "转账成功", value: 1},
        {key: "转账异常", value: -1},
      ],
      // 支付详情/转账支付密码
      rules: {
        payPassword: [
          {required: true, message: '请输入支付密码', trigger: 'blur'}
        ]
      },
      // 修改订单
      payRules: {
        identity: [
          {required: true, message: '请输入支付宝账号', trigger: 'blur'},
        ],
        mobile: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]{9}$/,
            required: false,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
        ],
        outBizNo: [
          {required: true, message: '请输入订单编号', trigger: 'blur'},
        ],
        transAmount: [
          {required: true, message: '请输入金额(单位：分)', trigger: 'blur'},
        ],
      },
      userList: [],
      valString: "", // 全选字符串
      selectUserLoading: false, // 用户下拉框加载
      tableData: [],
      fileList: [], // 上传后的数据
      pageInfo: {
        pageNo: 1, // 当前页数
        pageSize: 10, // 当前每页显示多少条
        pageSizeArr: [10, 20, 30, 40],
        totalNum: 12, // 总数
        totalPage: 1
      }
    }
  },
  props: {
    tableStatus: {
      required: true,
      default: () => 1
    },
  },
  watch: {
    'formInline.timeForm': {
      deep: true,
      handler: function (newV) {
        let startTime = newV[0] ? dayjs(newV[0]).format("YYYY-MM-DD HH:mm:ss") : "";
        let endTime = newV[1] ? dayjs(newV[1]).format("YYYY-MM-DD HH:mm:ss") : "";
        this.formInline.startTime = startTime;
        this.formInline.endTime = endTime;
      }
    }
  },
  computed: {
    // 设置请求头 token
    uploadHeaders() {
      return {
        'token': this.token
      }
    }
  },
  methods: {
    thStyleFun() {
      return 'text-align:center'
    },
    cellStyleFun() {
      return 'text-align:center'
    },
    getNowColumn(value){
      if(this.tableStatus == '-1') {
        this.payFormErrorVisible = true;
        this.payForm = value;
      }
    },
    // 初始化数据
    searchOrderListByPage(pageNo, pageSize) {
      const pageInfo = {
        ...this.formInline,
        status: this.tableStatus,
        currentPage: pageNo,
        rows: pageSize
      }
      orderList.post(pageInfo).then(res => {
        this.tableData.splice(0, this.tableData.length);
        if (res && res.code == 1000) {
          let data = res.data;
          data.records.map(item => {
            item.transAmount = this.fenZhuanYuanChange(item.transAmount);
            item.statusTxt = this.statusTxt[item.status];
            this.tableData.push(item);
          });
          let dataPageInfo = {
            pageNo: data.current,
            pageSize: data.size,
            totalNum: data.total,
            totalPage: data.pages
          };
          Object.assign(this.pageInfo, dataPageInfo);
          this.pageInfo.pageNo = pageNo;
        }
      });
    },
    // 添加用户模态框
    handleEdit() {
      this.editForm = {...this.payForm};
      this.editFormVisible = true;
      this.title = '修改订单';
    },
    fenZhuanYuanChange(fen) {
      if (fen <= 0) {
        return fen;
      }
      let yuan = fen / 100.0;
      return yuan.toFixed(2);
    },
    // 订单处理模态框
    handlePay(index, row) {
      let statusTxt = "";
      if (row.status === 0) {
        this.payFormVisible = true;
        statusTxt = "未处理"
      } else if (row.status === 1) {
        this.payFormVisible = true;
        statusTxt = "处理成功"
      } else {
        this.payFormErrorVisible = true;
        statusTxt = "处理异常"
      }
      this.payForm = {
        name: row.name,
        operatorId: row.operatorId,
        identity: row.identity,
        outBizNo: row.outBizNo,
        transAmount: row.transAmount,
        transDate: row.transDate,
        status: statusTxt,
        ipAddr: row.ipAddr,
        remark: row.remark,
        createTime: row.createTime,
        mobile: row.mobile,
        updateTime: row.updateTime,
      };
    },
    // 表格全选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      let arr = [];
      val.map(item => {
        arr.push(item.outBizNo)
      });
      this.valString = arr.toString();
    },
    // 批量转账
    handleTransfer() {
      if (!this.valString) {
        this.$message.error('必须要选择一项数据！')
        return;
      }
      this.trFormVisible = true;
    },
    // 批量添加订单
    handleAddOrder() {
    },
    handleDel(index, row) {
      const data = {outBizNo: row.outBizNo};
      this.$confirm('此操作将会把 订单号：' + row.outBizNo + ' 删除，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        orderDel.post(data).then(res => {
          if (res.code != 1000) this.$message.error('删除订单失败!');
          this.$message.success('删除订单成功!');
          this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
        });
      }).catch(() => {
      });

    },
    // 监听 pageSize 每页显示多少条
    handleSizeChange(val) {
      this.pageInfo.pageSize = val;
      this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
    },
    // 监听 页码值 改变事件
    onSelectPageHandler(index) {
      this.searchOrderListByPage(index, this.pageInfo.pageSize);
    },
    // 关闭编辑、增加弹出框
    closeDialog(t) {
      if (t == 'edit') {
        this.editFormVisible = false;
        this.editForm = {...this.editForm};
      } else if (t == 'pay') {
        this.payFormVisible = false;
        this.payForm = {...this.payForm};
      } else if (t == 'error') {
        this.payFormErrorVisible = false;
        this.payForm = {...this.payForm};
      } else {
        this.trFormVisible = false;
        this.trForm = "";
      }
    },
    // 搜索按钮
    searchOrderBtn() {
      this.formInline.status = this.tableStatus;
      this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize)
    },
    clearSearch(name) {
      this.formInline[name] = "";
      this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize)
    },
    handleSearchSelectChange(value) {
      if (value == null) {
        this.formInline.startTime = "";
        this.formInline.endTime = "";
      }
      this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize)
    },
    handleUserDataSelectChange() {
      this.getUserList();
    },
    // 清除搜索参数
    delOrderBtn() {
      this.formInline = {
        name: "",
        operatorId: "",
        identity: "",
        outBizNo: "",
        transAmount: "",
        status: this.tableStatus
      };
      this.$message.success("清除搜索参数成功!");
      this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize)

    },
    getUserList() {
      if (!this.userList.length) {
        this.selectUserLoading = true;
        const pageInfo = {currentPage: 1, rows: 100}
        getList.post(pageInfo).then(res => {
          this.userList = res.data.records;
          this.selectUserLoading = false;
        });
      }
    },
    submitPayForm() {
      this.$refs['editPayForm'].validate(valid => {
        if (valid) {
          const data = {
            outBizNo: this.payForm.outBizNo,
            payPassword: this.payForm.payPassword,
          };
          orderTransfer.post(data).then(res => {
            if (res.code != 1000) {
              this.$message.error("支付密码设置失败!");
              return;
            }
            this.$message.success("支付密码设置成功!");
            this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
          });
        } else {
          return false
        }
      });
    },
    // 获取异常信息
    getErrorInfoByNum() {
      const data = {
        outBizNo: this.payForm.outBizNo
      };
      orderReason.post(data).then(res => {
        if (res.code !== 1000) {
          this.$message.error("获取数据失败!");
          return;
        }
        this.ErrorMsg = res.data.subMsg
      });
    },
    // 批量转账
    submitTrForm() {
      this.$refs['trForm'].validate(valid => {
        if (valid) {
          const data = {
            outBizNos: this.valString,
            payPassword: this.payForm.payPassword,
          };
          orderTransferBatch.post(data).then(res => {
            if (res.code != 1000) {
              this.$message.error(res.desc);
              return;
            }
            this.$message.success("批量转账成功!");
            this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
          });
        } else {
          return false
        }
      });
    },
    // 编辑、添加提交方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          // 请求方法
          this.editForm.transAmount = this.editForm.transAmount * 100;
          orderMod.post(this.editForm).then(res => {
            this.editFormVisible = false;
            this.payFormErrorVisible = false;
            this.loading = false;
            if (res.code != 1000) {
              this.$message.error(res.desc)
              return;
            }
            this.$message.success("订单修改成功！")
            this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
          });
        } else {
          return false
        }
      })
    }
  },
  created() {
    this.searchOrderListByPage(this.pageInfo.pageNo, this.pageInfo.pageSize);
  }
}
</script>